import IndexUtils from "@/utils/IndexUtils"; // 通用工具封装
import "./header.less" // 组件使用的样式 less
import logo from "~/assets/logo.png" // logo
import header_tel from "~/assets/icon/header-tel.png"
import header_tpl from "./header_com.tpl" // 组件模板 <template>

class Header extends HTMLElement {
    content: ParentNode
    header_root: HTMLElement

    // 生命周期 - created
    constructor() {
        super();
        // this.shadow = this.attachShadow({mode: 'closed'}); // 影子dom 使用后可以隔离外部样式影响 但无法使用全局注册工具 和 引入外部样式
        const templateElem: HTMLTemplateElement = <HTMLTemplateElement>IndexUtils.Instance.parseDom(header_tpl())
        this.content = <ParentNode>templateElem.content.cloneNode(true);
        this.header_root = this.content.querySelector("#header_root")!
        this.initAttribute()
        this.appendChild(this.content);
    }

    initAttribute() {
        this.headerSetAttribute("#logo_img", "src", logo)
        this.headerSetAttribute("#phone_img", "src", header_tel)
    }

    headerSetAttribute(selector: string, attr: string, value: any): void {
        this.content.querySelector(selector)!.setAttribute(attr, value)
    }

    // 生命周期 - mounted
    connectedCallback() {
        // 注册滚动条监听 使用节流优化
        window.addEventListener("scroll",IndexUtils.Instance.throttle(this.scrollTop_header.bind(this),200,true).bind(this))
    }

    scrollTop_header(): void {
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        console.log(scrollTop)
        if (scrollTop > 20) {
            this.header_root.style.backgroundColor = "#212230"
        } else {
            this.header_root.style.backgroundColor = "transparent"
        }
    }

    // 生命周期 - update
    attributeChangedCallback() {
        console.log('connectedCallback被执行');
    }

    // 生命周期 - delete
    disconnectedCallback() {
        console.log('被移出')
    }
}

export default Header